clear
set more off

cap log close
log using $logdir/time_series.log, replace

use ertc ertc_amendment tp ffcra using $fromsasdir/result, clear
drop if ertc > 900*10^6 // data error
gen any_ertc = ertc + ertc_amendment > 0

gcollapse (max) max_ertc = ertc max_amend = ertc_amendment ///
    (sum) count_ertc = any_ertc ertc ertc_amendment ffcra (mean) any_ertc, by(tp) fast

qui sum count_ertc
assert r(min) >= 5

gen ratio_ertc = max_ertc/ertc
qui sum ratio_ertc
assert r(max) <= 0.4

gen ratio_amend = max_amend/ertc_amendment
qui sum ratio_amend
assert r(max) <= 0.4


gen year = floor(tp/100)
gen q = mod(tp,100)/3
gen date = yq(year,q)
format date %tq

qui replace ertc = ertc/10^9
qui replace ertc_amendment = ertc_amendment/10^9
qui replace ffcra = ffcra/10^9

twoway connected ertc date || ///
    connected ertc_amendment date, lpattern("__") msymbol(square) ///
	legend(order(1 "Dollars on original return" 2 "Dollars on amended returns") cols(1)) ///
	scheme(s1color) ///
	xtitle("Quarter") ytitle("Dollars of ERTC (bil)")

qui save $outdir/time_series, replace

list
qui sum ertc
di r(sum)
qui sum ertc_amendment
di r(sum)

cap log close
